﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Services;

namespace MyLib.Web {
	/// <summary>
	/// 
	/// </summary>
	[System.ComponentModel.DesignerCategory("Code")]
	[Obsolete("Resources leak error! See 'm_sessionFactory'.", true)]
	public abstract class MyWebService : WebService, IDbContext {
		/// <summary>
		/// 
		/// </summary>
		protected log4net.ILog m_logger;

		private SessionFactory m_sessionFactory;

		private IDictionary<Type, DbContextProvider> m_cachedProviders;

		/// <summary>
		/// 
		/// </summary>
		protected MyWebService() {
			m_logger = log4net.LogManager.GetLogger(GetType());

			m_cachedProviders = new Dictionary<Type, DbContextProvider>();

			m_sessionFactory = SessionFactory.Create();
		}

		#region IDbContext

		SessionFactory IDbContext.SessionFactory {
			get {
				System.Diagnostics.Debug.Assert(m_sessionFactory != null);
				return m_sessionFactory;
			}
		}

		#endregion

		/// <summary>
		/// 
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <returns></returns>
		protected internal T GetDbProvider<T>() where T : DbContextProvider, new() {
			return (T)GetDbProvider(typeof(T));
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="pType"></param>
		/// <returns></returns>
		internal DbContextProvider GetDbProvider(Type pType) {
			DbContextProvider t = null;

			if (m_cachedProviders.ContainsKey(pType)) {
				t = m_cachedProviders[pType];
			} else {
				t = Activator.CreateInstance(pType) as DbContextProvider;

				if (t != null) {
					t.SessionFactory = ((IDbContext)this).SessionFactory;

					m_cachedProviders.Add(pType, t);
				}
			}

			return t;
		}
	} // end of MyWebService.
}
